package org.jeecg.modules.travel.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.travel.dto.feedback.AppFeedbackPageDto;
import org.jeecg.modules.travel.dto.feedback.FeedbackAddDto;
import org.jeecg.modules.travel.dto.feedback.FeedbackAnswerDto;
import org.jeecg.modules.travel.entity.JhAttraction;
import org.jeecg.modules.travel.entity.JhAttractionFile;
import org.jeecg.modules.travel.mapper.JhAttractionFileMapper;
import org.jeecg.modules.travel.mapper.JhAttractionMapper;
import org.jeecg.modules.travel.mapper.JhFeedbackMapper;
import org.jeecg.modules.travel.entity.JhFeedback;
import org.jeecg.modules.travel.service.IJhFeedbackService;
import org.jeecg.modules.travel.util.AMapUtils;
import org.jeecg.modules.travel.vo.CompositeKey;
import org.jeecg.modules.travel.vo.attractionFile.AttractionFileVo;
import org.jeecg.modules.travel.vo.feedback.AppFeedbackRecordVo;
import org.jeecg.modules.travel.vo.feedback.JhFeedbackVo;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 用户反馈表
 * @Author: jeecg-boot
 * @Date:   2025-04-19
 * @Version: V1.0
 */
@Service
@Slf4j
public class JhFeedbackServiceImpl extends ServiceImpl<JhFeedbackMapper, JhFeedback> implements IJhFeedbackService {

    @Resource
    private JhAttractionMapper attractionMapper;
    @Resource
    private ISysUserService sysUserService;

    @Resource
    private JhAttractionFileMapper jhAttractionFileMapper;

    @Override
    public String coupleBack(FeedbackAddDto dto) {
        JhAttraction attraction = attractionMapper.selectById(dto.getAttractionId());
        if(attraction == null) {
            return "景区未找到，请联系管理员";
        }
        JhFeedback feedback = new JhFeedback();
        feedback.setUserId(dto.getUserId());
        feedback.setAttractionId(dto.getAttractionId());
        feedback.setFeedbackType(dto.getFeedbackType());
        feedback.setFeedbackContent(dto.getFeedbackContent());
        feedback.setFeedbackStatus("0");
        save(feedback);
        return null;
    }

    @Override
    public IPage<AppFeedbackRecordVo> appFeedbackPageList(AppFeedbackPageDto dto,Page<JhFeedback> page, QueryWrapper<JhFeedback> queryWrapper) {
        IPage<AppFeedbackRecordVo> pageList = baseMapper.appFeedbackPageList(page,queryWrapper);
        if (pageList.getRecords() != null && !pageList.getRecords().isEmpty()) {
            List<String> ids = pageList.getRecords().stream()
                    .map(AppFeedbackRecordVo::getAttractionId).collect(Collectors.toList());
            List<JhAttraction> attractionList = attractionMapper.selectBatchIds(ids);
            Map<String,JhAttraction> attractionMap = attractionList.stream().collect(Collectors.toMap(JhAttraction::getId, i -> i));
            List<JhAttractionFile> list = jhAttractionFileMapper.selectList(new QueryWrapper<JhAttractionFile>()
                    .lambda().in(JhAttractionFile::getAttractionId,ids));
            Map<CompositeKey, List<AttractionFileVo>> fileMap = list.stream().collect(Collectors
                    .groupingBy(item -> new CompositeKey(item.getAttractionId(),item.getType()), Collectors.mapping(
                            i -> AttractionFileVo.builder().type(i.getType()).path(i.getPath()).build(),
                            Collectors.toList()
                    )));
            for (AppFeedbackRecordVo record : pageList.getRecords()) {
                if (attractionMap.get(record.getAttractionId()) != null) {
                    JhAttraction attraction = attractionMap.get(record.getAttractionId());
                    record.setAttractionName(attraction.getAttractionName());
                    record.setAttractionTheme(attraction.getAttractionTheme());
                    record.setAttractionDescription(attraction.getAttractionDescription());
                    record.setAttractionRecommendedDuration(attraction.getAttractionRecommendedDuration());
                    record.setAttractionCapacity(attraction.getAttractionCapacity());
                    record.setIsFeatured(attraction.getIsFeatured());
                    record.setAttractionHeat(attraction.getAttractionHeat());
                    record.setAttractionStatus(attraction.getAttractionStatus());
                    record.setBusinessHour(attraction.getBusinessHour());
                    record.setAttractionCountry(attraction.getAttractionCountry());
                    record.setAttractionProvince(attraction.getAttractionProvince());
                    record.setAttractionCity(attraction.getAttractionCity());
                    record.setAttractionDistrict(attraction.getAttractionDistrict());
                    record.setAreaCode(attraction.getAreaCode());
                    record.setAttractionAddress(attraction.getAttractionAddress());
                    record.setLongitude(attraction.getLongitude());
                    record.setLatitude(attraction.getLatitude());
                    record.setContactName(attraction.getContactName());
                    record.setContactPhone(attraction.getContactPhone());
                    record.setWebsite(attraction.getWebsite());
                    if (dto.getLon() != null && dto.getLat() != null) {
                        int distance = AMapUtils.getDistance(dto.getLon(), dto.getLat(), attraction.getLongitude(), attraction.getLatitude());
                        record.setDistance(BigDecimal.valueOf(distance).divide(new BigDecimal(1000),2, RoundingMode.HALF_UP));
                    }
                }
                List<AttractionFileVo> imgFile = fileMap.get(new CompositeKey(record.getId(), 0));
                List<AttractionFileVo> MpFile = fileMap.get(new CompositeKey(record.getId(), 1));
                List<AttractionFileVo> videoFile = fileMap.get(new CompositeKey(record.getId(), 2));
                record.setImgFile(imgFile == null ? new ArrayList<>() : imgFile);
                record.setMpFile(MpFile == null ? new ArrayList<>() : MpFile);
                record.setVideoFile(videoFile == null ? new ArrayList<>() : videoFile);
            }
        }
        return pageList;
    }

    @Override
    public String answer(String userNameByToken, FeedbackAnswerDto feedbackDto) {
        SysUser userByName = sysUserService.getUserByName(userNameByToken);
        String id = feedbackDto.getId();
        //更新
        LambdaUpdateWrapper<JhFeedback> jhFeedbackLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        jhFeedbackLambdaUpdateWrapper.eq(JhFeedback::getId, id);
        JhFeedback byId = this.getOne(jhFeedbackLambdaUpdateWrapper);

        //避免null异常
        if (byId == null) {
            log.error("反馈信息不存在，反馈ID：{}", feedbackDto.getId());
            return "反馈信息不存在，请刷新后重试";
        }
        byId.setResponseUserId(userByName.getId());
        byId.setResponseContent(feedbackDto.getText());
        // 使用Hutool的DateUtil格式化日期，精确到分钟
        byId.setResponseTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
        byId.setFeedbackStatus("3"); // 设置状态为已回复
        return this.saveOrUpdate(byId) ? "" : "回复失败";
    }

    @Override
    public IPage<JhFeedbackVo> queryPageList(Page<JhFeedback> page, QueryWrapper<JhFeedback> queryWrapper) {
        return baseMapper.queryPageList(page, queryWrapper);
    }

}
